<!DOCTYPE html>
<html lang="en" color-mode="light">

  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="keywords" content="JavaScript,Hexo" />
  <meta name="author" content="超能虾米" />
  <meta name="description" content="" />
  
  
  <title>
    
      Java8 Stream 
      
      
      |
    
     超能虾米的博客
  </title>

  
    <link rel="apple-touch-icon" href="/images/favicon.png">
    <link rel="icon" href="/images/favicon.png">
  

  <!-- Raleway-Font -->
  <link href="https://fonts.googleapis.com/css?family=Raleway&display=swap" rel="stylesheet">

  <!-- hexo site css -->
  <link rel="stylesheet" href="/css/main.css" />
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1886449_67xjft27j1l.css" />
  <!-- 代码块风格 -->
  

  <!-- jquery3.3.1 -->
  
    <script defer type="text/javascript" src="/plugins/jquery.min.js"></script>
  

  <!-- fancybox -->
  
    <link href="/plugins/jquery.fancybox.min.css" rel="stylesheet">
    <script defer type="text/javascript" src="/plugins/jquery.fancybox.min.js"></script>
  
  
<script src="/js/fancybox.js"></script>


  

  

  <script>
    var html = document.documentElement
    const colorMode = localStorage.getItem('color-mode')
    if (colorMode) {
      document.documentElement.setAttribute('color-mode', colorMode)
    }
  </script>
<meta name="generator" content="Hexo 5.4.2"><link rel="alternate" href="/atom.xml" title="超能虾米的博客" type="application/atom+xml">
</head>


  <body>
    <div id="app">
      <div class="header">
  <div class="avatar">
    <a href="/">
      <!-- 头像取消懒加载，添加no-lazy -->
      
        <img src="/images/头像.JPEG" alt="">
      
    </a>
    <div class="nickname"><a href="/">超能虾米</a></div>
  </div>
  <div class="navbar">
    <ul>
      
        <li class="nav-item" data-path="/">
          <a href="/">主页</a>
        </li>
      
        <li class="nav-item" data-path="/archives/">
          <a href="/archives/">归档</a>
        </li>
      
        <li class="nav-item" data-path="/categories/">
          <a href="/categories/">分类</a>
        </li>
      
        <li class="nav-item" data-path="/tags/">
          <a href="/tags/">标签</a>
        </li>
      
        <li class="nav-item" data-path="/friends/">
          <a href="/friends/">朋友</a>
        </li>
      
        <li class="nav-item" data-path="/about/">
          <a href="/about/">关于我</a>
        </li>
      
    </ul>
  </div>
</div>


<script src="/js/activeNav.js"></script>



      <div class="flex-container">
        <!-- 文章详情页，展示文章具体内容，url形式：https://yoursite/文章标题/ -->
<!-- 同时为「标签tag」，「朋友friend」，「分类categories」，「关于about」页面的承载页面，具体展示取决于page.type -->


  <!-- LaTex Display -->

  
    <script async type="text/javascript" src="/plugins/mathjax/tex-chtml.js"></script>
  
  <script>
    MathJax = {
      tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']]
      }
    }
  </script>





  <!-- clipboard -->

  
    <script async type="text/javascript" src="/plugins/clipboard.min.js"></script>
  
  
<script src="/js/codeCopy.js"></script>







  

  

  

  
  <!-- 文章内容页 url形式：https://yoursite/文章标题/ -->
  <div class="container post-details" id="post-details">
    <div class="post-content">
      <div class="post-title">Java8 Stream</div>
      <div class="post-attach">
        <span class="post-pubtime">
          <i class="iconfont icon-updatetime mr-10" title="Update time"></i>
          2021-09-23 16:48:14
        </span>
        
              <span class="post-categories">
                <i class="iconfont icon-bookmark" title="Categories"></i>
                
                <span class="span--category">
                  <a href="/categories/Java8/" title="Java8">
                    <b>#</b> Java8
                  </a>
                </span>
                
                <span class="span--category">
                  <a href="/categories/Java8/Java/" title="Java">
                    <b>#</b> Java
                  </a>
                </span>
                
                <span class="span--category">
                  <a href="/categories/Java8/Java/%E5%90%8E%E7%AB%AF/" title="后端">
                    <b>#</b> 后端
                  </a>
                </span>
                
                <span class="span--category">
                  <a href="/categories/Java8/Java/%E5%90%8E%E7%AB%AF/Java/" title="Java">
                    <b>#</b> Java
                  </a>
                </span>
                
              </span>
          
              <span class="post-tags">
                <i class="iconfont icon-tags mr-10" title="Tags"></i>
                
                <span class="span--tag mr-8">
                  <a href="/tags/Java/" title="Java">
                    #Java
                  </a>
                </span>
                
                <span class="span--tag mr-8">
                  <a href="/tags/Stream/" title="Stream">
                    #Stream
                  </a>
                </span>
                
              </span>
          
      </div>
      <div class="markdown-body">
        <p><a target="_blank" rel="noopener" href="https://blog.csdn.net/mu_wind/article/details/109516995">这里引用一个Stream的博客</a></p>
<p><img src="http://qiniu.c77544s.top/picgo/202210121453117.png" alt="Java Stream流"></p>
<p><code>Stream</code> 可以由数组或集合创建，对流的操作分为两种：</p>
<p>中间操作，每次返回一个新的流，可以有多个。<br>终端操作，每个流只能进行一次终端操作，终端操作结束后流无法再次使用。终端操作会产生一个新的集合或值。<br>另外，<code>Stream</code>有几个特性：</p>
<ol>
<li>stream不存储数据，而是按照特定的规则对数据进行计算，一般会输出结果。</li>
<li>stream不会改变数据源，通常情况下会产生一个新的集合或一个值。</li>
<li>stream具有延迟执行特性，只有调用终端操作时，中间操作才会执行。</li>
</ol>
<h1 id="Stream的创建方式"><a href="#Stream的创建方式" class="headerlink" title="Stream的创建方式"></a>Stream的创建方式</h1><h2 id="1、通过-java-util-Collection-stream-方法用集合创建流"><a href="#1、通过-java-util-Collection-stream-方法用集合创建流" class="headerlink" title="1、通过 java.util.Collection.stream() 方法用集合创建流"></a>1、通过 <code>java.util.Collection.stream()</code> 方法用集合创建流</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; list = Arrays.asList(<span class="string">&quot;a&quot;</span>, <span class="string">&quot;b&quot;</span>, <span class="string">&quot;c&quot;</span>);</span><br><span class="line"><span class="comment">// 创建一个顺序流</span></span><br><span class="line">Stream&lt;String&gt; stream = list.stream();</span><br><span class="line"><span class="comment">// 创建一个并行流</span></span><br><span class="line">Stream&lt;String&gt; parallelStream = list.parallelStream();</span><br></pre></td></tr></table></figure>

<h2 id="2、使用java-util-Arrays-stream-T-array-方法用数组创建流"><a href="#2、使用java-util-Arrays-stream-T-array-方法用数组创建流" class="headerlink" title="2、使用java.util.Arrays.stream(T[] array)方法用数组创建流"></a>2、使用<code>java.util.Arrays.stream(T[] array)</code>方法用数组创建流</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span>[] array=&#123;<span class="number">1</span>,<span class="number">3</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">8</span>&#125;;</span><br><span class="line"><span class="type">IntStream</span> <span class="variable">stream</span> <span class="operator">=</span> Arrays.stream(array);</span><br></pre></td></tr></table></figure>

<h2 id="3、使用Stream的静态方法：of-、iterate-、generate"><a href="#3、使用Stream的静态方法：of-、iterate-、generate" class="headerlink" title="3、使用Stream的静态方法：of()、iterate()、generate()"></a>3、使用<code>Stream</code>的静态方法：<code>of()、iterate()、generate()</code></h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Stream&lt;Integer&gt; stream = Stream.of(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>);</span><br><span class="line"></span><br><span class="line">Stream&lt;Integer&gt; stream2 = Stream.iterate(<span class="number">0</span>, (x) -&gt; x + <span class="number">3</span>).limit(<span class="number">4</span>);</span><br><span class="line">stream2.forEach(System.out::println);</span><br><span class="line"></span><br><span class="line">Stream&lt;Double&gt; stream3 = Stream.generate(Math::random).limit(<span class="number">3</span>);</span><br><span class="line">stream3.forEach(System.out::println);</span><br></pre></td></tr></table></figure>

<h1 id="Stream的使用"><a href="#Stream的使用" class="headerlink" title="Stream的使用"></a>Stream的使用</h1><h2 id="遍历-x2F-匹配"><a href="#遍历-x2F-匹配" class="headerlink" title="遍历&#x2F;匹配"></a>遍历&#x2F;匹配</h2><p><code>forEach()</code> <code>findFirst()</code> <code>findAny()</code> <code>anyMatch()</code> <code>allMatch</code> <code>noneMatch()</code></p>
<h2 id="筛选-x2F-过滤"><a href="#筛选-x2F-过滤" class="headerlink" title="筛选&#x2F;过滤"></a>筛选&#x2F;过滤</h2><p><code>filter()</code></p>
<h2 id="聚合"><a href="#聚合" class="headerlink" title="聚合"></a>聚合</h2><p><code>max()</code> <code>min()</code> <code>count()</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Optional&lt;String&gt; max = list.stream().max(Comparator.comparing(String::length));</span><br><span class="line">Optional&lt;Integer&gt; max2 = list.stream().max(<span class="keyword">new</span> <span class="title class_">Comparator</span>&lt;Integer&gt;() &#123;</span><br><span class="line">			<span class="meta">@Override</span></span><br><span class="line">			<span class="keyword">public</span> <span class="type">int</span> <span class="title function_">compare</span><span class="params">(Integer o1, Integer o2)</span> &#123;</span><br><span class="line">				<span class="keyword">return</span> o1.compareTo(o2);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;);</span><br><span class="line"><span class="type">long</span> <span class="variable">count</span> <span class="operator">=</span> list.stream().filter(x -&gt; x &gt; <span class="number">6</span>).count();</span><br></pre></td></tr></table></figure>

<h2 id="映射"><a href="#映射" class="headerlink" title="映射"></a>映射</h2><p><code>map</code> <code>flatMap</code></p>
<ul>
<li><code>map</code>：接收一个函数作为参数，该函数会被应用到每个元素上，并将其映射成一个新的元素。</li>
<li><code>flatMap</code>：接收一个函数作为参数，将流中的每个值都换成另一个流，然后把所有流连接成一个流。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; list = Arrays.asList(<span class="string">&quot;m,k,l,a&quot;</span>, <span class="string">&quot;1,3,5,7&quot;</span>);</span><br><span class="line">List&lt;String&gt; listNew = list.stream().flatMap(s -&gt; &#123;</span><br><span class="line">  <span class="comment">// 将每个元素转换成一个stream</span></span><br><span class="line">  String[] split = s.split(<span class="string">&quot;,&quot;</span>);</span><br><span class="line">  Stream&lt;String&gt; s2 = Arrays.stream(split);</span><br><span class="line">  <span class="keyword">return</span> s2;</span><br><span class="line">&#125;).collect(Collectors.toList());</span><br></pre></td></tr></table></figure>

<blockquote>
<p>结果：[m, k, l, a, 1, 3, 5]</p>
</blockquote>
<h2 id="规约（reduce）"><a href="#规约（reduce）" class="headerlink" title="规约（reduce）"></a>规约（reduce）</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">T <span class="title function_">reduce</span><span class="params">(T identity, BinaryOperator&lt;T&gt; accumulator)</span>;</span><br><span class="line">Optional&lt;T&gt; <span class="title function_">reduce</span><span class="params">(BinaryOperator&lt;T&gt; accumulator)</span>;</span><br><span class="line">&lt;U&gt; U <span class="title function_">reduce</span><span class="params">(U identity, BiFunction&lt;U, ? <span class="built_in">super</span> T, U&gt; accumulator, BinaryOperator&lt;U&gt; combiner)</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">Integer</span> <span class="variable">sumSalary1</span> <span class="operator">=</span> personList.stream().map(Person::getSalary).reduce(<span class="number">0</span>, Integer::sum);</span><br><span class="line">Optional&lt;Integer&gt; sumSalary2 = personList.stream().map(Person::getSalary).reduce(Integer::sum);</span><br><span class="line"><span class="type">Integer</span> <span class="variable">sumSalary3</span> <span class="operator">=</span> personList.stream().reduce(<span class="number">0</span>, (sum, p) -&gt; sum += p.getSalary(), Integer::sum);</span><br></pre></td></tr></table></figure>

<h2 id="收集"><a href="#收集" class="headerlink" title="收集"></a>收集</h2><p><code>collect</code>，收集，可以说是内容最繁多、功能最丰富的部分了。从字面上去理解，就是把一个流收集起来，最终可以是收集成一个值也可以收集成一个新的集合。</p>
<blockquote>
<p><code>collect</code>主要依赖<code>java.util.stream.Collectors</code>类内置的静态方法。</p>
</blockquote>
<h3 id="归集-toList-x2F-toSet-x2F-toMap"><a href="#归集-toList-x2F-toSet-x2F-toMap" class="headerlink" title="归集(toList&#x2F;toSet&#x2F;toMap)"></a>归集(toList&#x2F;toSet&#x2F;toMap)</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">List&lt;Integer&gt; listNew = list.stream().filter(x -&gt; x % <span class="number">2</span> == <span class="number">0</span>).collect(Collectors.toList());</span><br><span class="line">Set&lt;Integer&gt; set = list.stream().filter(x -&gt; x % <span class="number">2</span> == <span class="number">0</span>).collect(Collectors.toSet());</span><br><span class="line">Map&lt;?, Person&gt; map = personList.stream().filter(p -&gt; p.getSalary() &gt; <span class="number">8000</span>).collect(Collectors.toMap(Person::getName, p -&gt; p));</span><br></pre></td></tr></table></figure>

<h3 id="统计-count-x2F-averaging"><a href="#统计-count-x2F-averaging" class="headerlink" title="统计(count&#x2F;averaging)"></a>统计(count&#x2F;averaging)</h3><p><code>Collectors</code>提供了一系列用于数据统计的静态方法：</p>
<ul>
<li>计数：<code>count</code></li>
<li>平均值：<code>averagingInt</code>、<code>averagingLong</code>、<code>averagingDouble</code></li>
<li>最值：<code>maxBy</code>、<code>minBy</code></li>
<li>求和：<code>summingInt</code>、<code>summingLong</code>、<code>summingDouble</code></li>
<li>统计以上所有：<code>summarizingInt</code>、<code>summarizingLong</code>、<code>summarizingDouble</code></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 求总数</span></span><br><span class="line"><span class="type">Long</span> <span class="variable">count</span> <span class="operator">=</span> personList.stream().collect(Collectors.counting());</span><br><span class="line"><span class="comment">// 求平均工资</span></span><br><span class="line"><span class="type">Double</span> <span class="variable">average</span> <span class="operator">=</span> personList.stream().collect(Collectors.averagingDouble(Person::getSalary));</span><br><span class="line"><span class="comment">// 求最高工资</span></span><br><span class="line">Optional&lt;Integer&gt; max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));</span><br><span class="line"><span class="comment">// 求工资之和</span></span><br><span class="line"><span class="type">Integer</span> <span class="variable">sum</span> <span class="operator">=</span> personList.stream().collect(Collectors.summingInt(Person::getSalary));</span><br><span class="line"><span class="comment">// 一次性统计所有信息</span></span><br><span class="line"><span class="type">DoubleSummaryStatistics</span> <span class="variable">collect</span> <span class="operator">=</span> personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));</span><br></pre></td></tr></table></figure>

<h3 id="分区-x2F-分组-partitioningBy-x2F-groupingBy"><a href="#分区-x2F-分组-partitioningBy-x2F-groupingBy" class="headerlink" title="分区&#x2F;分组(partitioningBy&#x2F;groupingBy)"></a>分区&#x2F;分组(partitioningBy&#x2F;groupingBy)</h3><ul>
<li>分区：将<code>stream</code>按条件分为两个<code>Map</code>，比如员工按薪资是否高于8000分为两部分。</li>
<li>分组：将集合分为多个Map，比如员工按性别分组。有单级分组和多级分组</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 将员工按薪资是否高于8000分组</span></span><br><span class="line">Map&lt;Boolean, List&lt;Person&gt;&gt; part = personList.stream().collect(Collectors.partitioningBy(x -&gt; x.getSalary() &gt; <span class="number">8000</span>));</span><br><span class="line"><span class="comment">// 将员工按性别分组</span></span><br><span class="line">Map&lt;String, List&lt;Person&gt;&gt; group = personList.stream().collect(Collectors.groupingBy(Person::getSex));</span><br><span class="line"><span class="comment">// 将员工先按性别分组，再按地区分组</span></span><br><span class="line">Map&lt;String, Map&lt;String, List&lt;Person&gt;&gt;&gt; group2 = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));</span><br></pre></td></tr></table></figure>

<h3 id="接合-joining"><a href="#接合-joining" class="headerlink" title="接合(joining)"></a>接合(joining)</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; list = Arrays.asList(<span class="string">&quot;A&quot;</span>, <span class="string">&quot;B&quot;</span>, <span class="string">&quot;C&quot;</span>);</span><br><span class="line"><span class="type">String</span> <span class="variable">string</span> <span class="operator">=</span> list.stream().collect(Collectors.joining(<span class="string">&quot;-&quot;</span>));</span><br></pre></td></tr></table></figure>

<h3 id="归约-reducing"><a href="#归约-reducing" class="headerlink" title="归约(reducing)"></a>归约(reducing)</h3><p><code>Collectors</code>类提供的<code>reducing</code>方法，相比于<code>stream</code>本身的<code>reduce</code>方法，增加了对自定义归约的支持。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 每个员工减去起征点后的薪资之和（这个例子并不严谨，但一时没想到好的例子）</span></span><br><span class="line"><span class="type">Integer</span> <span class="variable">sum</span> <span class="operator">=</span> personList.stream().collect(Collectors.reducing(<span class="number">0</span>, Person::getSalary, (i, j) -&gt; (i + j - <span class="number">5000</span>)));</span><br><span class="line">System.out.println(<span class="string">&quot;员工扣税薪资总和：&quot;</span> + sum);</span><br><span class="line"></span><br><span class="line"><span class="comment">// stream的reduce</span></span><br><span class="line">Optional&lt;Integer&gt; sum2 = personList.stream().map(Person::getSalary).reduce(Integer::sum);</span><br><span class="line">System.out.println(<span class="string">&quot;员工薪资总和：&quot;</span> + sum2.get());</span><br></pre></td></tr></table></figure>

<h2 id="排序-sorted"><a href="#排序-sorted" class="headerlink" title="排序(sorted)"></a>排序(sorted)</h2><p>sorted，中间操作。有两种排序：</p>
<ul>
<li>sorted()：自然排序，流中元素需实现Comparable接口</li>
<li>sorted(Comparator com)：Comparator排序器自定义排序</li>
</ul>
<h2 id="提取-x2F-组合"><a href="#提取-x2F-组合" class="headerlink" title="提取&#x2F;组合"></a>提取&#x2F;组合</h2><p><code>distinct()</code> <code>limit()</code> <code>skip()</code></p>

      </div>
      
        <div class="prev-or-next">
          <div class="post-foot-next">
            
              <a href="/2021/09/17/%E5%90%8E%E7%AB%AF/Mybatis/Mybatis%E7%AC%94%E8%AE%B0/" target="_self">
                <i class="iconfont icon-chevronleft"></i>
                <span>Prev</span>
              </a>
            
          </div>
          <div class="post-attach">
            <span class="post-pubtime">
              <i class="iconfont icon-updatetime mr-10" title="Update time"></i>
              2021-09-23 16:48:14
            </span>
            
                  <span class="post-categories">
                    <i class="iconfont icon-bookmark" title="Categories"></i>
                    
                    <span class="span--category">
                      <a href="/categories/Java8/" title="Java8">
                        <b>#</b> Java8
                      </a>
                    </span>
                    
                    <span class="span--category">
                      <a href="/categories/Java8/Java/" title="Java">
                        <b>#</b> Java
                      </a>
                    </span>
                    
                    <span class="span--category">
                      <a href="/categories/Java8/Java/%E5%90%8E%E7%AB%AF/" title="后端">
                        <b>#</b> 后端
                      </a>
                    </span>
                    
                    <span class="span--category">
                      <a href="/categories/Java8/Java/%E5%90%8E%E7%AB%AF/Java/" title="Java">
                        <b>#</b> Java
                      </a>
                    </span>
                    
                  </span>
              
                  <span class="post-tags">
                    <i class="iconfont icon-tags mr-10" title="Tags"></i>
                    
                    <span class="span--tag mr-8">
                      <a href="/tags/Java/" title="Java">
                        #Java
                      </a>
                    </span>
                    
                    <span class="span--tag mr-8">
                      <a href="/tags/Stream/" title="Stream">
                        #Stream
                      </a>
                    </span>
                    
                  </span>
              
          </div>
          <div class="post-foot-prev">
            
              <a href="/2021/09/24/%E5%90%8E%E7%AB%AF/Java/Optional%E7%B1%BB/" target="_self">
                <span>Next</span>
                <i class="iconfont icon-chevronright"></i>
              </a>
            
          </div>
        </div>
      
    </div>
    
  <div id="btn-catalog" class="btn-catalog">
    <i class="iconfont icon-catalog"></i>
  </div>
  <div class="post-catalog hidden" id="catalog">
    <div class="title">Contents</div>
    <div class="catalog-content">
      
        <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Stream%E7%9A%84%E5%88%9B%E5%BB%BA%E6%96%B9%E5%BC%8F"><span class="toc-text">Stream的创建方式</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E9%80%9A%E8%BF%87-java-util-Collection-stream-%E6%96%B9%E6%B3%95%E7%94%A8%E9%9B%86%E5%90%88%E5%88%9B%E5%BB%BA%E6%B5%81"><span class="toc-text">1、通过 java.util.Collection.stream() 方法用集合创建流</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E4%BD%BF%E7%94%A8java-util-Arrays-stream-T-array-%E6%96%B9%E6%B3%95%E7%94%A8%E6%95%B0%E7%BB%84%E5%88%9B%E5%BB%BA%E6%B5%81"><span class="toc-text">2、使用java.util.Arrays.stream(T[] array)方法用数组创建流</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E4%BD%BF%E7%94%A8Stream%E7%9A%84%E9%9D%99%E6%80%81%E6%96%B9%E6%B3%95%EF%BC%9Aof-%E3%80%81iterate-%E3%80%81generate"><span class="toc-text">3、使用Stream的静态方法：of()、iterate()、generate()</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Stream%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-text">Stream的使用</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%81%8D%E5%8E%86-x2F-%E5%8C%B9%E9%85%8D"><span class="toc-text">遍历&#x2F;匹配</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AD%9B%E9%80%89-x2F-%E8%BF%87%E6%BB%A4"><span class="toc-text">筛选&#x2F;过滤</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%81%9A%E5%90%88"><span class="toc-text">聚合</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%98%A0%E5%B0%84"><span class="toc-text">映射</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A7%84%E7%BA%A6%EF%BC%88reduce%EF%BC%89"><span class="toc-text">规约（reduce）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%94%B6%E9%9B%86"><span class="toc-text">收集</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BD%92%E9%9B%86-toList-x2F-toSet-x2F-toMap"><span class="toc-text">归集(toList&#x2F;toSet&#x2F;toMap)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BB%9F%E8%AE%A1-count-x2F-averaging"><span class="toc-text">统计(count&#x2F;averaging)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%86%E5%8C%BA-x2F-%E5%88%86%E7%BB%84-partitioningBy-x2F-groupingBy"><span class="toc-text">分区&#x2F;分组(partitioningBy&#x2F;groupingBy)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8E%A5%E5%90%88-joining"><span class="toc-text">接合(joining)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BD%92%E7%BA%A6-reducing"><span class="toc-text">归约(reducing)</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8E%92%E5%BA%8F-sorted"><span class="toc-text">排序(sorted)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8F%90%E5%8F%96-x2F-%E7%BB%84%E5%90%88"><span class="toc-text">提取&#x2F;组合</span></a></li></ol></li></ol>
      
    </div>
  </div>

  
<script src="/js/catalog.js"></script>




    
      <div class="comments-container">
        




  
    <script async type="text/javascript" src="/plugins/valine.min.js" onload="loadValineSuc(this)"></script>
  

  <div id="vcomments"></div>

  <script>
    function loadValineSuc() {
      new Valine({
        el: '#vcomments',
        appId: 'H2QqshKF8elT2Si5bfKynT9h-9Nh9j0Va',
        appKey: 'WgtVppOWkTZ8fWNReNI1Ymf7',
        placeholder: '有问题请留言吧!',
        avatar: 'retro',
        lang: 'en'
      })
    }
  </script>

    <style>
      .comments-container .v .vempty {
        display: none!important;
      }
    </style>




      </div>
    
  </div>


        
<div class="footer">
  <div class="social">
    <ul>
      
        <li>
          <a title="github" target="_blank" rel="noopener" href="https://github.com/zchengsite/hexo-theme-oranges">
            <i class="iconfont icon-github"></i>
          </a>
        </li>
      
        <li>
          <a title="email" target="_blank" rel="noopener" href="https://c77544s.github.io/about/">
            <i class="iconfont icon-envelope"></i>
          </a>
        </li>
      
        <li>
          <a title="wechat" target="_blank" rel="noopener" href="https://c77544s.github.io/about/">
            <i class="iconfont icon-wechat"></i>
          </a>
        </li>
      
        <li>
          <a title="rss" href="/atom.xml">
            <i class="iconfont icon-rss"></i>
          </a>
        </li>
      
    </ul>
  </div>
  
    
    <div class="footer-more">
      
        <a target="_blank" rel="noopener" href="https://github.com/zchengsite/hexo-theme-oranges">Copyright © 2023 Oranges</a>
        
    </div>
  
    
    <div class="footer-more">
      
        <a target="_blank" rel="noopener" href="https://github.com/zchengsite/hexo-theme-oranges">Theme by Oranges | Powered by Hexo</a>
        
    </div>
  
  
</div>

      </div>

      <div class="tools-bar">
        <div class="back-to-top tools-bar-item hidden">
  <a href="javascript: void(0)">
    <i class="iconfont icon-chevronup"></i>
  </a>
</div>


<script src="/js/backtotop.js"></script>



        
  <div class="search-icon tools-bar-item" id="search-icon">
    <a href="javascript: void(0)">
      <i class="iconfont icon-search"></i>
    </a>
  </div>

  <div class="search-overlay hidden">
    <div class="search-content" tabindex="0">
      <div class="search-title">
        <span class="search-icon-input">
          <a href="javascript: void(0)">
            <i class="iconfont icon-search"></i>
          </a>
        </span>
        
          <input type="text" class="search-input" id="search-input" placeholder="搜索...">
        
        <span class="search-close-icon" id="search-close-icon">
          <a href="javascript: void(0)">
            <i class="iconfont icon-close"></i>
          </a>
        </span>
      </div>
      <div class="search-result" id="search-result"></div>
    </div>
  </div>

  <script type="text/javascript">
    var inputArea = document.querySelector("#search-input")
    var searchOverlayArea = document.querySelector(".search-overlay")

    inputArea.onclick = function() {
      getSearchFile()
      this.onclick = null
    }

    inputArea.onkeydown = function() {
      if(event.keyCode == 13)
        return false
    }

    function openOrHideSearchContent() {
      let isHidden = searchOverlayArea.classList.contains('hidden')
      if (isHidden) {
        searchOverlayArea.classList.remove('hidden')
        document.body.classList.add('hidden')
        // inputArea.focus()
      } else {
        searchOverlayArea.classList.add('hidden')
        document.body.classList.remove('hidden')
      }
    }

    function blurSearchContent(e) {
      if (e.target === searchOverlayArea) {
        openOrHideSearchContent()
      }
    }

    document.querySelector("#search-icon").addEventListener("click", openOrHideSearchContent, false)
    document.querySelector("#search-close-icon").addEventListener("click", openOrHideSearchContent, false)
    searchOverlayArea.addEventListener("click", blurSearchContent, false)

    var searchFunc = function (path, search_id, content_id) {
      'use strict';
      var $input = document.getElementById(search_id);
      var $resultContent = document.getElementById(content_id);
      $resultContent.innerHTML = "<ul><span class='local-search-empty'>First search, index file loading, please wait...<span></ul>";
      $.ajax({
        // 0x01. load xml file
        url: path,
        dataType: "xml",
        success: function (xmlResponse) {
          // 0x02. parse xml file
          var datas = $("entry", xmlResponse).map(function () {
            return {
              title: $("title", this).text(),
              content: $("content", this).text(),
              url: $("url", this).text()
            };
          }).get();
          $resultContent.innerHTML = "";

          $input.addEventListener('input', function () {
            // 0x03. parse query to keywords list
            var str = '<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length <= 0) {
              return;
            }
            // 0x04. perform local searching
            datas.forEach(function (data) {
              var isMatch = true;
              var content_index = [];
              if (!data.title || data.title.trim() === '') {
                data.title = "Untitled";
              }
              var orig_data_title = data.title.trim();
              var data_title = orig_data_title.toLowerCase();
              var orig_data_content = data.content.trim().replace(/<[^>]+>/g, "");
              var data_content = orig_data_content.toLowerCase();
              var data_url = data.url;
              var index_title = -1;
              var index_content = -1;
              var first_occur = -1;
              // only match artiles with not empty contents
              if (data_content !== '') {
                keywords.forEach(function (keyword, i) {
                  index_title = data_title.indexOf(keyword);
                  index_content = data_content.indexOf(keyword);

                  if (index_title < 0 && index_content < 0) {
                    isMatch = false;
                  } else {
                    if (index_content < 0) {
                      index_content = 0;
                    }
                    if (i == 0) {
                      first_occur = index_content;
                    }
                    // content_index.push({index_content:index_content, keyword_len:keyword_len});
                  }
                });
              } else {
                isMatch = false;
              }
              // 0x05. show search results
              if (isMatch) {
                str += "<li><a href='" + data_url + "' class='search-result-title'>" + orig_data_title + "</a>";
                var content = orig_data_content;
                if (first_occur >= 0) {
                  // cut out 100 characters
                  var start = first_occur - 20;
                  var end = first_occur + 80;

                  if (start < 0) {
                    start = 0;
                  }

                  if (start == 0) {
                    end = 100;
                  }

                  if (end > content.length) {
                    end = content.length;
                  }

                  var match_content = content.substr(start, end);

                  // highlight all keywords
                  keywords.forEach(function (keyword) {
                    var regS = new RegExp(keyword, "gi");
                    match_content = match_content.replace(regS, "<span class=\"search-keyword\">" + keyword + "</span>");
                  });

                  str += "<p class=\"search-result-abstract\">" + match_content + "...</p>"
                }
                str += "</li>";
              }
            });
            str += "</ul>";
            if (str.indexOf('<li>') === -1) {
              return $resultContent.innerHTML = "<ul><span class='local-search-empty'>No result<span></ul>";
            }
            $resultContent.innerHTML = str;
          });
        },
        error: function(xhr, status, error) {
          $resultContent.innerHTML = ""
          if (xhr.status === 404) {
            $resultContent.innerHTML = "<ul><span class='local-search-empty'>The search.xml file was not found, please refer to：<a href='https://github.com/zchengsite/hexo-theme-oranges#configuration' target='_black'>configuration</a><span></ul>";
          } else {
            $resultContent.innerHTML = "<ul><span class='local-search-empty'>The request failed, Try to refresh the page or try again later.<span></ul>";
          }
        }
      });
      $(document).on('click', '#search-close-icon', function() {
        $('#search-input').val('');
        $('#search-result').html('');
      });
    }

    var getSearchFile = function() {
        var path = "/search.xml";
        searchFunc(path, 'search-input', 'search-result');
    }
  </script>




        
  <div class="tools-bar-item theme-icon" id="switch-color-scheme">
    <a href="javascript: void(0)">
      <i id="theme-icon" class="iconfont icon-moon"></i>
    </a>
  </div>

  
<script src="/js/colorscheme.js"></script>





        
  
    <div class="share-icon tools-bar-item">
      <a href="javascript: void(0)" id="share-icon">
        <i class="iconfont iconshare"></i>
      </a>
      <div class="share-content hidden">
        
          <a class="share-item" href="https://twitter.com/intent/tweet?text=' + Java8%20Stream + '&url=' + http%3A%2F%2Fc77544s.gitee.io%2F2021%2F09%2F23%2F%25E5%2590%258E%25E7%25AB%25AF%2FJava%2FJava8-Stream%2F + '" target="_blank" title="Twitter">
            <i class="iconfont icon-twitter"></i>
          </a>
        
        
          <a class="share-item" href="https://www.facebook.com/sharer.php?u=http://c77544s.gitee.io/2021/09/23/%E5%90%8E%E7%AB%AF/Java/Java8-Stream/" target="_blank" title="Facebook">
            <i class="iconfont icon-facebooksquare"></i>
          </a>
        
      </div>
    </div>
  
  
<script src="/js/shares.js"></script>



      </div>
    </div>
  </body>
</html>
